import {
  FooterToolbar,
  PageContainer,
  ProCard,
  ProForm,
  ProFormDigit,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
} from '@ant-design/pro-components';
import { Space, message, Button } from 'antd';

import {
  queryResourcesList,
  saveOrUpdate,
  queryResourceDetail,
} from '@/services/resource-management';
import useDetailType from '@/hooks/useDetailType';

const ResourceDetail: React.FC = () => {
  const { isModify, isRead, params, goBack, goReplace } =
    useDetailType<Record<'id', string | undefined>>();
  const { id } = params;

  /**
   * 获取资源详情
   * @param detailId
   * @returns
   */
  const getResourceDetail = async (detailId: string) => {
    const res = await queryResourceDetail({ id: detailId });
    if (!res.code && res.data) {
      return res.data;
    }
    return {} as API.ResourceDetail;
  };

  /**
   * 父级资源
   * @returns
   */
  const getResourceList = async () => {
    const res = await queryResourcesList({
      pageNum: 1,
      pageSize: 100,
      enable: 1,
    });
    if (!res.code && res.data) {
      const list = res.data?.content || [];
      return list.map((l) => ({
        label: l.name,
        value: l.id,
      }));
    }
    return [];
  };

  /**
   * 提交保存
   * @param values
   */
  const onFinish = async (values: API.ResourceDetail) => {
    if (id) values.id = id;
    const res = await saveOrUpdate({
      parentId: '',
      deleted: 0,
      ...values,
    });
    if (!res.code && res.data) {
      message.success('提交成功');
      goReplace('/system/resource/list');
      return;
    } else {
      message.error(res.message || '提交失败');
    }
  };

  /**
   * 初始化
   * @returns
   */
  const init = async () => {
    if ((isModify || isRead) && !!id) {
      return getResourceDetail(id);
    }
    return {} as API.ResourceDetail;
  };

  return (
    <PageContainer>
      <ProCard>
        <ProForm<API.ResourceDetail>
          layout="horizontal"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 10 }}
          request={init}
          submitter={{
            render: (_, dom) => (
              <FooterToolbar
                extra={
                  <div style={{ textAlign: 'center', padding: '5px 0' }}>
                    {isRead ? (
                      <Button onClick={goBack}>返回</Button>
                    ) : (
                      <Space>
                        <Button onClick={goBack}>取消</Button>
                        {dom[1]}
                      </Space>
                    )}
                  </div>
                }
              />
            ),
          }}
          onFinish={onFinish}
        >
          <ProFormText
            name="name"
            label="资源名称"
            tooltip="资源名称长度1-20个字符"
            placeholder="请输入资源名称"
            readonly={isRead}
            required
            rules={[
              {
                required: true,
                message: '请输入资源名称',
              },
              {
                min: 1,
                message: '角色名称长度1-20个字符',
              },
              {
                max: 20,
                message: '角色名称长度1-20个字符',
              },
            ]}
          />
          <ProFormSelect
            name="type"
            label="类型"
            placeholder="请选择类型"
            readonly={isRead}
            required
            convertValue={(e) => (!!e ? `${e}` : e)}
            valueEnum={{
              1: '菜单',
              2: '按钮',
            }}
            rules={[
              {
                required: true,
                message: '请输入资源名称',
              },
            ]}
          />
          <ProFormText name="icon" label="icon" placeholder="请输入图标" readonly={isRead} />
          <ProFormText name="route" label="路由" placeholder="请输入路由" readonly={isRead} />
          <ProFormSelect
            name="parentId"
            label="父级资源"
            placeholder="请选择父级资源"
            readonly={isRead}
            showSearch
            request={getResourceList}
          />
          <ProFormDigit
            name="sort"
            label="序号"
            placeholder="请输入序号"
            required
            readonly={isRead}
            fieldProps={{
              min: 0,
              max: 999,
              precision: 0,
            }}
            rules={[
              {
                required: true,
                message: '请输入序号',
              },
            ]}
          />
          <ProFormSwitch
            name="enable"
            label="状态"
            placeholder="请输入序号"
            readonly={isRead}
            transform={(e) => ({ enable: !!e ? 1 : 0 })}
          />
          <ProFormSwitch
            name="hideInMenu"
            label="隐藏菜单"
            placeholder="请输入序号"
            readonly={isRead}
            transform={(e) => ({ hideInMenu: !!e ? 1 : 0 })}
          />
        </ProForm>
      </ProCard>
    </PageContainer>
  );
};

export default ResourceDetail;
